/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import domain.Sex;
import domain.Student;
import java.io.IOException;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Database;
import model.*;

/**
 *
 * @author user
 */
public class SaveStudent extends HttpServlet {

    private Database db = Database.getInstance();
    private final String ACTION_CREATE = "create";
    private final String ACTION_EDIT = "edit";
    Model model = new ModelImpl();

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            request.setCharacterEncoding("utf8");
            //String userPath = request.getServletPath();
            String action = request.getParameter("action");

            int id = -1;

            String pageTo = "index.jsp";

            Student student = (Student) FabricaBeanCreate.createBean(Student.class, request);
            request.setAttribute("student", student);

            if (action.equals(ACTION_CREATE)) {
//                    db.addStudent(student);
                model.addObject(student);
                System.out.println("student = " + student);
            } else if (action.equals(ACTION_EDIT)) {
                if (!request.getParameter("id").isEmpty()) {
                    id = Integer.parseInt(request.getParameter("id"));
                }
                student.setId(id);
                model.modifyObject(student);
                // db.editStudent(student);
            }
            pageTo = "/WEB-INF/view/studentConfirm.jsp";

            RequestDispatcher rd = request.getRequestDispatcher(pageTo);
            rd.forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
